package prom

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/prometheus/common/version"
	"io/ioutil"
	"net/http"
)

type Client struct {
	head *http.Header
	url  string
}

func OpenProm(url string) (*Client, error) {
	head := &http.Header{}
	head.Add("Content-Encoding", "snappy")
	head.Set("Content-Type", "application/x-protobuf")
	head.Set("User-Agent", fmt.Sprintf("Prometheus/%s", version.Version))
	head.Set("X-Prometheus-Remote-Write-Version", "0.1.0")
	return &Client{
		url:  url,
		head: head,
	}, nil
}

func (r *Client) WriteData(data []byte) error {
	httpReq, err := http.NewRequest("POST", "http://"+r.url+"/api/v1/write", bytes.NewReader(data))
	if err != nil {
		return err
	}
	httpReq.Header = *r.head

	if _, err = http.DefaultClient.Do(httpReq); err != nil {
		return err
	}

	return nil
}

//func (r *Client) Query(query, time string) error {
//	//http.Get(fmt.Sprintf("dddd %v  fdsfds%v"))
//	return nil
//}

func (r *Client) QueryRules(user string) interface{} {
	var data rules
	res, err := http.Get("http://" + r.url + "/api/v1/rules")
	if err != nil {
		data.Status += err.Error()
		return data.Status
	}
	bts, err := ioutil.ReadAll(res.Body)
	if err != nil {
		data.Status += err.Error()
		return data.Status
	}
	if err = json.Unmarshal(bts, &data); err != nil {
		data.Status += err.Error()
		return data.Status
	}

	var userData interface{}
	for _, v := range data.Data.Groups {
		rule, ok := v.(map[string]interface{})
		if !ok {

		}
		userName, ok := rule["name"]
		if userName == user {
			userData = v
			break
		}
	}
	data.Data.Groups = []interface{}{userData}
	return data
}

func (r *Client) QueryAlerts(user string) interface{} {
	var data rules
	res, err := http.Get("http://" + r.url + "/api/v1/rules?type=alert")
	if err != nil {
		data.Status += err.Error()
		return data.Status
	}
	bts, err := ioutil.ReadAll(res.Body)
	if err != nil {
		data.Status += err.Error()
		return data.Status
	}

	if err = json.Unmarshal(bts, &data); err != nil {
		data.Status += err.Error()
		return data.Status
	}

	var userData interface{}
	for _, v := range data.Data.Groups {
		rule, ok := v.(map[string]interface{})
		if !ok {

		}
		userName, ok := rule["name"]
		if userName == user {
			userData = v
			break
		}
	}
	data.Data.Groups = []interface{}{userData}
	return data
}

type rules struct {
	Status string `json:"status"`
	Data   struct {
		Groups []interface{} `json:"groups"`
	} `json:"data"`
}
